package model

import (
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"time"
)

type Cart struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	UserId    int       `gorm:"not null" json:"user_id"`
	UserInfo  User      `gorm:"foreignkey:UserId" json:"user_info"`
	GoodsInfo Goods     `gorm:"foreignkey:GoodsId" json:"goods_info"`
	GoodsId   int       `gorm:"not null" json:"goods_id"`
	Checked   bool      `gorm:"default:false; not null" json:"checked"`
	Count     int       `gorm:"not null" json:"count"`
	Price     int       `gorm:"not null" json:"price"`
}

// 新增购物车纪录
func CreateCart(data *Cart) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	} else {
		return errmsg.SUCCESS
	}
}

/*
获取所有购物车数据
pageNum 当前页号
pageSize当前页大小
*/
func GetCartList(user_id int) structs.JSONResponse {
	var cart []Cart
	var total int
	var list []interface{}
	tx := db.Model(&cart).Where("ID >0")
	if user_id > 0 {
		tx = tx.Where("user_id = ?", user_id)
	} else {
		return helpers.Error("ID 不存在")
	}
	tx = tx.Preload("UserInfo")
	tx = tx.Preload("GoodsInfo")
	tx.Count(&total)
	err := tx.Find(&cart).RecordNotFound()
	if err {
		return helpers.Error("")
	}
	for _, v := range cart {
		list = append(list, v)
	}
	response := helpers.Success(list)
	return response
}

// 更新购物车
func UpdateCart(data *Cart) int {
	var cart Cart
	var maps = make(map[string]interface{})
	maps["count"] = data.Count
	maps["price"] = data.Price
	maps["checked"] = data.Checked
	err := db.Model(&cart).Where("id = ?", data.ID).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 删除购物车纪录
func DeleteCart(id int) int {
	var data Cart
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err = db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR_USER_NOT_EXIST
}
